package com.demo.search;

import java.io.File;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.similar.MoreLikeThis;
import org.apache.lucene.store.FSDirectory;

public class BooksMoreLikeThis {
	public static void main(String[] args) throws Throwable {
		String indexDir = System.getProperty("index.dir");
		indexDir = "C:\\development\\lucence\\index";
		FSDirectory directory = FSDirectory.open(new File(indexDir));
		IndexReader reader = IndexReader.open(directory);
		IndexSearcher searcher = new IndexSearcher(reader);
		int numDocs = reader.maxDoc();
		MoreLikeThis mlt = new MoreLikeThis(reader);
		mlt.setFieldNames(new String[] { "contents", "windows"});
		mlt.setMinTermFreq(1); 	// 默认值是2，建议自己做限制，否则可能查不出结果
		mlt.setMinDocFreq(1); 	// 默认值是5，建议自己做限制，否则可能查不出结果
		for (int docID = 0; docID < numDocs; docID++) {
			System.out.println();
			Document doc = reader.document(docID);
			System.out.println(doc.get("title"));
			Query query = mlt.like(docID);
			System.out.println(" query = " + query);
			TopDocs similarDocs = searcher.search(query, 10);
			if (similarDocs.totalHits == 0)
				System.out.println(" None like this");
			for (int i = 0; i < similarDocs.scoreDocs.length; i++) {
				if (similarDocs.scoreDocs[i].doc != docID) {
					doc = reader.document(similarDocs.scoreDocs[i].doc);
					System.out.println(" -> "
							+ doc.getField("filename").stringValue() + "  >>>>>> " + doc.getFieldable("contents").stringValue());
				}
			}
		}
		searcher.close();
		reader.close();
		directory.close();
	}
}